package com.jishucai.servlet;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.internal.StringUtil;


/**
 * @author qiaowang 2021/4/15
 */
public class DefaultCustomHttpResponse implements CustomHttpResponse{

    private HttpRequest request;

    private ChannelHandlerContext context;

    public DefaultCustomHttpResponse(HttpRequest request, ChannelHandlerContext channelHandlerContext) {
        this.request = request;
        this.context = channelHandlerContext;
    }

    @Override
    public void write(String content) throws Exception {
        if (StringUtil.isNullOrEmpty(content)) {
            return;
        }
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(content.getBytes("utf-8"))
        );

        HttpHeaders headers = response.headers();
        headers.set(HttpHeaderNames.CONTENT_TYPE, "text/json");
        headers.set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        headers.set(HttpHeaderNames.EXPIRES, 0);

        if (HttpUtil.isKeepAlive(request)) {
            headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }

        context.writeAndFlush(response);
    }
}
